package com.xidian.zhiancloud.controller.ledgerManagerment.targetAndSystem;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xidian.zhiancloud.constant.LedgerManagementConstant;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.model.SecurityProductionTargetLedger;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.ledgerManagerment.targetAndSystem.SecurityProductionTargetLedgerQO;
import com.xidian.zhiancloud.service.ledgerManager.targerAndSystem.SecurityProductionTargetLedgerService;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.service.user.usermanage.OrganizationService;
import com.xidian.zhiancloud.vo.ledgerManagerment.targetAndSystem.SecurityProductionTargetLedgerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 台账管理 目标职责与制度 安全生产目标台账
 *
 * @Author: Summerless
 * @Date: 2020/11/7 11:48
 */
@RestController
@RequestMapping("/SecurityProductionTargetLedger")
public class SecurityProductionTargetLedgerController extends BaseController {
    @Autowired
    private SecurityProductionTargetLedgerService securityProductionTargetLedgerService;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private UserService userService;

    /**
     * 增加安全生产目标台账对象
     *
     * @param securityProductionTargetLedger 安全生产目标台账对象
     * @return 是否增加成功
     */
    @PostMapping("/add")
    public ResultDTO<Boolean> add(SecurityProductionTargetLedger securityProductionTargetLedger) {
        securityProductionTargetLedger.setCreatorId(getSessionUserid());
        securityProductionTargetLedger.setCompanyId(getSessionUserCompanyId());
        securityProductionTargetLedger.setCreateTime(new Date(System.currentTimeMillis()));
        Boolean res = securityProductionTargetLedgerService.save(securityProductionTargetLedger);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id获取安全生产目标台账对象
     *
     * @param id 安全生产目标台账对象的id
     * @return 安全生产目标台账对象
     */
    @GetMapping("/getById")
    public ResultDTO<SecurityProductionTargetLedgerVO> getById(@RequestParam("id") Long id) {
        return ResultDTO.successOf(securityProductionTargetLedgerService.getVOById(id), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 根据id列表删除安全生产目标台账对象
     *
     * @param ids 安全生产目标台账对象的id列表
     * @return 是否删除成功
     */
    @PostMapping("/deleteByIds")
    public ResultDTO<Boolean> deleteByIds(Long[] ids) {
        Boolean res = securityProductionTargetLedgerService.removeByIds(Arrays.asList(ids));
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 修改安全生产目标台账对象
     *
     * @param securityProductionTargetLedger 安全生产目标台账对象
     * @return 是否修改成功
     */
    @PostMapping("/patchById")
    public ResultDTO<Boolean> patchById(SecurityProductionTargetLedger securityProductionTargetLedger) {
        securityProductionTargetLedger.setCompanyId(null);
        securityProductionTargetLedger.setCreatorId(null);
        securityProductionTargetLedger.setCreateTime(null);
        Boolean res = securityProductionTargetLedgerService.updateById(securityProductionTargetLedger);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }

    /**
     * 列表查询
     *
     * @param securityProductionTargetLedgerQO 查询参数
     * @return 安全生产目标台账列表
     */
    @GetMapping("/getListByQO")
    public ResultDTO<IPage<SecurityProductionTargetLedgerVO>> getList(SecurityProductionTargetLedgerQO securityProductionTargetLedgerQO) {
        if (securityProductionTargetLedgerQO.getCurrent() == null || securityProductionTargetLedgerQO.getSize() == null) {
            return ResultDTO.errorOf(GeneralResponseEnums.REQUEST_ERROR);
        }
        securityProductionTargetLedgerQO.setCompanyId(getSessionUserCompanyId());
        return ResultDTO.successOf(securityProductionTargetLedgerService.selectByQO(securityProductionTargetLedgerQO), GeneralResponseEnums.SUCCESS);
    }

    /**
     * 导出
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response, Long[] ids) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("安全生产目标台账导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<SecurityProductionTargetLedger> list = securityProductionTargetLedgerService.listByIds(Arrays.asList(ids));
        List<SecurityProductionTargetLedgerVO> ans = new LinkedList<>();
        list.forEach(t -> {
            SecurityProductionTargetLedgerVO vo = new SecurityProductionTargetLedgerVO();
            BeanUtils.copyProperties(t, vo);
            Organization organization = organizationService.getById(vo.getOrganizationId());
            vo.setSignOrganizationName(organization == null?"该部门已被删除":organization.getName());
            SysUser user = userService.getById(vo.getSignerId());
            vo.setSignerName(user == null ? "该用户已被删除" : user.getName());
            vo.setCompletionName(LedgerManagementConstant.Completion.get(vo.getCompletion()));
            ans.add(vo);
        });
        System.out.println(list.size());
        EasyExcel.write(response.getOutputStream(), SecurityProductionTargetLedgerVO.class).sheet("模板").doWrite(ans);
    }

    /**
     * 导入
     */
    @PostMapping("/upload")
    public ResultDTO<Boolean> upload(@RequestParam("file") MultipartFile file) throws IOException {
        List<SecurityProductionTargetLedgerVO> list = EasyExcel.read(file.getInputStream()).head(SecurityProductionTargetLedgerVO.class).sheet().doReadSync();
        List<SecurityProductionTargetLedger> ans = new LinkedList<>();
        list.forEach(vo -> {
            SecurityProductionTargetLedger ledger = new SecurityProductionTargetLedger();
            BeanUtils.copyProperties(vo, ledger);
            ledger.setCreatorId(getSessionUserid());
            ledger.setCompanyId(getSessionUserCompanyId());
            ledger.setCreateTime(new Date(System.currentTimeMillis()));
            LambdaQueryWrapper<Organization> organizationLambdaQueryWrapper = Wrappers.<Organization>lambdaQuery();
            organizationLambdaQueryWrapper.eq(Organization::getName,vo.getSignOrganizationName());
            Organization organization = organizationService.getOne(organizationLambdaQueryWrapper);
            if(organization!=null){
                ledger.setOrganizationId(organization.getId());
            }
            LambdaQueryWrapper<SysUser> query = Wrappers.<SysUser>lambdaQuery();
            query.eq(SysUser::getName,vo.getSignerName());
            SysUser user = userService.getOne(query);
            if(user != null){
                ledger.setSignerId(user.getId());
            }
            ledger.setCompletion(LedgerManagementConstant.Completion.indexOf(vo.getCompletionName()));
            ans.add(ledger);
        });
        Boolean res = securityProductionTargetLedgerService.saveBatch(ans);
        return ResultDTO.successOf(res, GeneralResponseEnums.SUCCESS);
    }
}
